<script setup>
import { ElMessage } from 'element-plus';
import {ref} from "vue";
import {userLoginService} from "@/api/account/account.js";
import {useTokenStore} from "@/stores/token.js";
import {useRouter} from "vue-router";

const router = useRouter();

const formData = ref({
  phone: "",
  password: ""
})

const formRef = ref(); // 表单引用

//调用useTokenStore得到状态
const tokenStore = useTokenStore();
//调用后台接口，完成登录
const login = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
        let result = await userLoginService(formData.value);
        if (result) {
          tokenStore.setToken(result.token);
          tokenStore.setRole(result.role)
          ElMessage.success(result.data ? result.data : '登录成功');
          await router.push('/');
        }
    }
  });
};

// 表单验证规则
const rules = ref({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
});
</script>

<template>
  <!-- 背景范围 -->
  <div class="login-page">
    <!--  登录框范围  -->
    <el-card class="box-card">
      <!--   标题范围   -->
      <div slot="header" class="clearfix">
        <span class="login-title">登录</span>
      </div><br>
      <!--   表单范围   -->
      <div class="login-form">
        <!--   登录表单    -->
        <el-form :model="formData" :rules="rules" ref="formRef">

          <el-form-item prop="phone">
            <el-input type="text" v-model="formData.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input type="password" v-model="formData.password"  placeholder="请输入密码"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button style="width:100%;" type="primary" @click="login" >登录</el-button>
          </el-form-item>
          <el-link type="info" @click="router.push('/register')">
            注册用户
          </el-link>
        </el-form>
      </div>
    </el-card>
  </div>
</template>


<style scoped>
.login-page{
  background-image: url('@/assets/images/background.jpg');
  background-size: cover; /* 背景图覆盖整个页面 */
  background-position: center; /* 背景图居中 */

  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-title{
  font-size: 20px;
  text-align: center;
}

.box-card {
  width: 500px;
  margin-left: 80vh;
}

</style>